<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑公告' : '新增公告' }}</span>
        </div>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        
        <el-form-item label="公告类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择公告类型" style="width: 100%">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="重要程度" prop="important">
          <el-switch
            v-model="form.important"
            :active-value="true"
            :inactive-value="false"
            active-text="重要"
            inactive-text="普通"
          />
        </el-form-item>
        
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            v-model="form.expireTime"
            type="datetime"
            placeholder="选择过期时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <WangEditor v-model="form.content" style="min-height:200px;" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">已发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button type="success" @click="submitAndPublish">保存并发布</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, FormRules } from 'element-plus'

import type { Announcement } from '@/types'
import WangEditor from '@/components/WangEditor.vue'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是编辑还是新增
const isEdit = computed(() => route.params.id !== undefined)

// 表单数据
const form = reactive<Partial<Announcement>>({
  title: '',
  content: '',
  type: 'notice',
  important: false,
  
  status: 'draft'
})

// 表单验证规则
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在2到100个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择公告类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' }
  ]
})

// 公告类型选项
const typeOptions = [
  { value: 'system', label: '系统公告' },
  { value: 'activity', label: '活动公告' },
  { value: 'notice', label: '通知' }
]

// 获取公告详情
const getDetail = async (id: string) => {
  loading.value = true
  try {
    // 这里可以调用实际的API
    // const res = await announcementApi.getDetail(id)
    // Object.assign(form, res.data)
    
    // 模拟数据
    setTimeout(() => {
      if (id === '1') {
        Object.assign(form, {
          id: '1',
          title: '系统升级通知',
          content: '系统将于2023年12月10日进行升级，届时系统将暂停服务2小时。',
          publisher: '系统管理员',
          publishTime: '2023-12-05 10:00:00',
          expireTime: '2023-12-12 00:00:00',
          status: 'published',
          important: true,
          type: 'system',
          readCount: 256
        })
      } else {
        Object.assign(form, {
          id: id,
          title: '测试公告',
          content: '这是一个测试公告内容',
          publisher: '',
          publishTime: null,
          expireTime: null,
          status: 'draft',
          important: false,
          type: 'notice',
          readCount: 0
        })
      }
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取公告详情失败:', error)
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        if (isEdit.value) {
          // 编辑
          // await announcementApi.update(route.params.id as string, form)
          ElMessage.success('更新成功')
        } else {
          // 新增
          // await announcementApi.create(form)
          ElMessage.success('添加成功')
        }
        loading.value = false
        
        // 返回列表页
        router.push('/content/announcement')
      } catch (error) {
        console.error('保存公告失败:', error)
        loading.value = false
        ElMessage.error('保存失败')
      }
    }
  })
}

// 保存并发布
const submitAndPublish = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      form.status = 'published'
      form.publishTime = new Date().toISOString()
      
      loading.value = true
      try {
        if (isEdit.value) {
          // 编辑
          // await announcementApi.update(route.params.id as string, form)
          ElMessage.success('更新并发布成功')
        } else {
          // 新增
          // await announcementApi.create(form)
          ElMessage.success('添加并发布成功')
        }
        loading.value = false
        
        // 返回列表页
        router.push('/content/announcement')
      } catch (error) {
        console.error('保存并发布公告失败:', error)
        loading.value = false
        ElMessage.error('保存失败')
      }
    }
  })
}

// 取消
const cancel = () => {
  router.push('/content/announcement')
}

// 生命周期
onMounted(() => {
  // 如果是编辑模式，获取详情
  if (isEdit.value && route.params.id) {
    getDetail(route.params.id as string)
  }
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  span {
    font-size: 18px;
    font-weight: bold;
  }
}
</style> 